package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.conf.ApplicationConf;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.ServiceUrlConst;
import com.authine.cloudpivot.ext.dto.*;
import com.authine.cloudpivot.ext.enums.FileExportEnum;
import com.authine.cloudpivot.ext.enums.OrderCustomerStatusEnum;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsStatusEnum;
import com.authine.cloudpivot.ext.model.ReportRecord;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.common.json.JsonUtils;
import com.authine.hermes.app.launcher.response.SingleResponse;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.*;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpMethod;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.cloudpivot.ext.conf.ApplicationConf.*;
import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("OrderInfoService")
public class OrderInfoService  extends ApplicationService {
    private final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    @Path("queryOrderdListInfo")
    @POST
    @Operation(summary = "查询下单", tags = CUSTOM_SERVICE)
    public com.alibaba.cola.dto.SingleResponse<BOList> queryOrderdListInfo(@Parameter OrderVendorGoodDto good) {
        PageObject<Map<String, Object>> pageObject = new PageObject<Map<String, Object>>();
        List<Map<String, Object>> orderList = null;
        int count = 0;
        try {
            Integer pageCurrent = good.getPageCurrent() == null ? 1 : good.getPageCurrent();
            Integer pageSize = good.getPageSize() == null ? 10 : good.getPageSize();
            // 设置当前页
            good.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = JdbcUtil.getCountSql(good);
            log.info("总条数:{}" + count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                orderList = JdbcUtil.getOrderList(good, start, pageSize);
            } else {
                pageObject.setPageCount(0);
                pageObject.setData(null);
            }
        } catch (Exception e) {
            log.info("查询出错", e);
        }

        BOList bolist = new BOList();
        bolist.setData(orderList);
        bolist.setTotal(count);
        bolist.setSchemaCode("ordered");
        return com.alibaba.cola.dto.SingleResponse.of(bolist);
    }


    /**
     * 客户订单详情-查看物流
     *
     * @param dto
     * @return
     */
    @Path("customerLogistics")
    @POST
    @Operation(summary = "客户订单详情-查看物流列表", tags = CUSTOM_SERVICE, description = "id、pageIndex、pageSize必填")
    public SingleResponse customerLogistics(@Parameter OrderCustomerGoodsDto dto) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.CUSTOMERLOGISTICS_URL);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        String execute = HttpClientUtil.execute(url, map);
        BOList boList = JSONObject.parseObject(execute, BOList.class);
        return SingleResponse.of(boList.getData().get(0));
    }

    /**
     * 查看退款记录
     *
     * @param dto
     * @return
     */
    @Path("customerRefundRecord")
    @POST
    @Operation(summary = "客户订单详情-查看退款记录", tags = CUSTOM_SERVICE, description = "id必填")
    public SingleResponse customerRefundRecord(@Parameter OrderCustomerGoodsDto dto) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.CUSTOMERREFUNDRECORD_URL);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        String execute = HttpClientUtil.execute(url, map);
        SingleResponse singleResponse = JSONObject.parseObject(execute, SingleResponse.class);
        return singleResponse;
    }


    /**
     * 客户订单详情-查看物流详情 调用订单中心的接口实现
     *
     * @param dto
     * @return
     */
    @Path("queryLogistics")
    @POST
    @Operation(summary = "公用接口-物流查询", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse queryLogistics(@Parameter LogisticsDto dto) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.QUERYLOGISTICS_URL);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        String execute = HttpClientUtil.execute(url, map);
        BOList boList = JSONObject.parseObject(execute, BOList.class);
        return SingleResponse.of(boList.getData().get(0));
    }
    /**
     * @param dto
     * @return
     */
    @Path("vendorRefundRecords")
    @POST
    @Operation(summary = "供应商订单详情-查看退款记录", tags = CUSTOM_SERVICE, description = "")
    public SingleResponse vendorRefundRecords(@Parameter OrderVendorGoodsDto dto) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.VENDOR_ORDER_DETAIL_URL);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        String execute = HttpClientUtil.execute(url, map);
        BOList boList = JSONObject.parseObject(execute, BOList.class);
        return SingleResponse.of(boList.getData().get(0));
    }


    /**
     * 获取表名称
     *
     * @param schemaCode
     * @return
     */
    public String getTableName(String schemaCode) {
        return tableHelper.getTableName(schemaCode);
    }

    @Path("exporDeliveryCrmGoodsReportexcel")
    @POST
    @Operation(summary = "供应商订单详情-导出发货单", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exporDeliveryCrmGoodsReportexcel(TraderSaveOrUpdateBo bo) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.EXPORDELIVERYCRMGOODSREPORTEXCEL_URL);
        Map<String, Object> map = BeanUtil.beanToMap(bo);
        String execute = HttpClientUtil.execute(url, map);
        SingleResponse singleResponse = JSONObject.parseObject(execute, SingleResponse.class);
        return singleResponse;
    }
    @Path("exporVendorOrderContractNoSealReport")
    @POST
    @Operation(summary = "供应商订单详情-导出采购单", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exporVendorOrderContractNoSealReport(SaveOrUpdateBO bo) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.VENDOR_PURCHASE_EXPORT_URL);
        Map<String, Object> map = BeanUtil.beanToMap(bo);
        String execute = HttpClientUtil.execute(url, map);
        SingleResponse singleResponse = JSONObject.parseObject(execute, SingleResponse.class);
        return singleResponse;
    }


    @Path("vendorLogistics")
    @POST
    @Operation(summary = "供应商订单详情-查看物流", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse vendorLogistics(OrderVendorGoodsDto bo) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.VENDOR_WULIU_URL);
        Map<String, Object> map = BeanUtil.beanToMap(bo);
        String execute = HttpClientUtil.execute(url, map);
        SingleResponse singleResponse = JSONObject.parseObject(execute, SingleResponse.class);
        return singleResponse;
    }


    /**
     * 待收货listBo
     *
     * @param dto
     * @return
     */
    @Path("customerDeliveryList")
    @POST
    @Operation(summary = "客户收货-待收货-待收货列表分页查询", tags = CUSTOM_SERVICE)
    public com.alibaba.cola.dto.SingleResponse<BOList> customerDeliveryList(@Parameter OrderCustomerGoodsDto dto) {
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsStatus()) && (dto.getOrderCustomerGoodsStatus().equals(OrderGoodsStatusEnum.DoneDelivery.name()) ||
                dto.getOrderCustomerGoodsStatus().equals(OrderGoodsStatusEnum.UpcomingDelivery.name()))) {
            dto.setOrderCustomerGoodsStatus(dto.getOrderCustomerGoodsStatus());
        } else {
            dto.setOrderCustomerGoodsStatus(OrderGoodsStatusEnum.DoneDelivery.name() + ";" + OrderGoodsStatusEnum.UpcomingDelivery.name());
        }
        return deliveryList(dto);
    }

    /**
     * 采购订单-待收货-待收货列表分页查询/客户收货-待收货-待收货列表分页查询
     *
     * @param dto
     * @return
     */
    public com.alibaba.cola.dto.SingleResponse<BOList> deliveryList(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------待收货列表分页查询 listBoDelivery Param：{}------------------------", JsonUtils.toJson(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return com.alibaba.cola.dto.SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder leftSql = new StringBuilder();
        StringBuilder groupBySql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select good.*,TIMESTAMPDIFF(hour,good.modifiedTime,now()) overHourTime,   GROUP_CONCAT(trace.logistics) logistics,trace.waybill waybill from ordercenter.i_ordercenter_t_order_customer_goods good  ");

        leftSql.append(" left join ordercenter.i_ordercenter_t_order_trace trace on trace.order_customer_goods_id = good.id and trace.deleted=0  ");

        countSql.append(" select count(1) from ( select count(*) from  ordercenter.i_ordercenter_t_order_customer_goods good  ");
        whereSql.append(" where good.deleted='0'");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and good.id in (:id) ");
            parameter.put("id", ids);
        }
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and good.order_customer_id in (:orderCustomerId) ");
            parameter.put("orderCustomerId", orderCustomerIds);
        }
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and good.order_vendor_id in (:orderVendorId) ");
            parameter.put("orderVendorId", orderVendorIds);
        }
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and good.vendor_organization_name like :vendorOrganizationName ");
            parameter.put("vendorOrganizationName", "%" + dto.getVendorOrganizationName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append(" and good.brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append(" and good.name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append(" and good.model like :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append(" and good.spec like :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsStatus())) {
            List<String> status = StringUtils.stringToListString(dto.getOrderCustomerGoodsStatus(), ";");
            whereSql.append(" and good.order_customer_goods_status in (:status) ");
            parameter.put("status", status);
        }

        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and good.place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(leftSql);
        countSql.append(whereSql);

        listSql.append(leftSql);
        listSql.append(whereSql);

        groupBySql.append(" group by good.id ");
        listSql.append(groupBySql);
        countSql.append(groupBySql);
        countSql.append(")a");
        listSql.append(" order by good.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------待收货列表分页查询 listBoDelivery listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> map : resultList) {
            //未发货数量=总数量-已退的-已发货数量+仅退货数量
            map.put("undelivered_quantity", getUndeliveredNum((String) map.get("id")));
//            //查询商品订单已签收数量
//            String tableNameGoodsReturns = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);
//            String tableNameOrderTrace = getTableName(ModelConst.T_ORDER_TRACE);
//            String sql = "select ((select sum(quantity) from " + tableNameGoodsReturns + " where order_customer_goods_id=:id group by order_customer_goods_id)-" +
//                    "(select sum(quantity) from " + tableNameOrderTrace + " where order_customer_goods_id=:id2 and type='ShippingLogistics' group by order_customer_goods_id)) as deliveryQuantity";
//            Map<String, Object> paraMap = new HashMap<>();
//            paraMap.put("id", map.get("id"));
//            paraMap.put("id2", map.get("id"));
//            Integer result = 0;
//            try {
//                result = jdbcTemplate.queryForObject(sql, paraMap, Integer.class);
//            } catch (DataAccessException e) {
//                e.printStackTrace();
//            }
//            //已签收数量
//            map.put("quantity_received", BigDecimalUtils.isNull(result));
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_CUSTOMER_GOODS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }
    public BigDecimal getUndeliveredNum(String orderCustomerGoodsId) {
        if (StringUtils.isBlank(orderCustomerGoodsId)) {
            return BigDecimal.ZERO;
        }
        Map<String, Object> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS)
                .selectField("(quantity-ifnull(quantity_return_not_shipped, 0.0)-ifnull(quantity_return_shipped, 0.0)-ifnull(quantity_shipped, 0.0)+ifnull(returned_num, 0.0)) as undelivered_num")
                .eq("id", orderCustomerGoodsId).queryForMap();
        return CollectionUtils.isEmpty(orderCustomerGoods)?BigDecimal.ZERO:BigDecimalUtils.isNull(orderCustomerGoods.get("undelivered_num"));
    }

    @Path("exportDeliveryOrder")
    @POST
    @Operation(summary = "客服工作台-全部订单-导出送货单", tags = CUSTOM_SERVICE)
    public SingleResponse exportDeliveryOrder(@Parameter ExportDto exportDto) {
        Assert.isTrue(Objects.nonNull(exportDto),"参数不能为空");
        com.alibaba.cola.exception.Assert.isTrue(!CollectionUtils.isEmpty(exportDto.getIds()),"id不能为空");
        com.alibaba.cola.exception.Assert.isTrue(!org.springframework.util.StringUtils.isEmpty(exportDto.getExportFileType()),"文件类型不能为空");

        BOList orderGoods = BoServiceUtils.findListBySimple(CUSTOMER_ORDER_GOODS, "id", exportDto.getIds(), Operator.IN).getData();
        List<Map<String, Object>> orderGoodsData = orderGoods.getData();
        com.alibaba.cola.exception.Assert.isTrue(!CollectionUtils.isEmpty(orderGoodsData),"查询订单商品不存在");

        String customerId = (String)CollectionUtils.firstElement(orderGoodsData).get("order_customer_id");
        BO order = BoServiceUtils.loadBo(customerId, CUSTOMERORDER).getData();
        com.alibaba.cola.exception.Assert.isTrue(!CollectionUtils.isEmpty(order.getData()),"查询客户订单不存在");
        Map<String, Object> customerOrder = order.getData();

        BO supplierOrderId = BoServiceUtils.loadBo((String)CollectionUtils.firstElement(orderGoodsData).get("order_vendor_id"), SUPPLIERORDER).getData();
        com.alibaba.cola.exception.Assert.isTrue(!CollectionUtils.isEmpty(supplierOrderId.getData()),"查询供应商订单不存在");
        Map<String, Object> supplierOrder = supplierOrderId.getData();

        List<Map<String, Object>> maps = orderGoodsData.stream().map(v -> {
            Map<String, Object> map = Maps.newHashMap();
            map.put("companyName", customerOrder.get("organization_name"));
            map.put("address", customerOrder.get("address"));
            map.put("fullName", customerOrder.get("receiver"));
            map.put("mobile", customerOrder.get("phone"));
            map.put("memo", supplierOrder.get("memo"));
            map.put("platformName", "上海固买供应链管理有限公司");
            map.put("goodsId", customerOrder.get("id").toString());
            map.put("customerOrderId", v.get("order_customer_id").toString());
            map.put("sku", v.get("sku"));
            map.put("name", v.get("name"));
            map.put("brand", v.get("brand"));
            map.put("spec", v.get("spec"));
            map.put("num", v.get("quantity").toString());
            map.put("unit", v.get("unit"));
            map.put("description", v.get("description"));
            map.put("erp", v.get("erp_po"));
            map.put("vendorOrderId", v.get("order_vendor_id"));
            map.put("price", v.get("price").toString());
            map.put("model", v.get("model"));
            map.put("customerOrderTime", v.get("place_order_time"));
            map.put("amount", v.get("amount").toString());
            return map;
        }).collect(Collectors.toList());
        ReportRecord record = ReportRecord.builder()
                .code("custom_delivery_goods_report")
                .type(Optional.ofNullable(FileExportEnum.get(exportDto.getExportFileType())).orElseThrow(()->new BizException("文件类型不支持")).getCode())
                .data(maps)
                .build();
        Map singleResponse = RestTemplateUtil.rest(Objects.requireNonNull(PmUtil.getUrl(systemManagement)).concat(EXPORT_REPORT_URL), record, HttpMethod.POST);
        com.alibaba.cola.dto.SingleResponse response = BoUtils.Map2Bo(singleResponse, com.alibaba.cola.dto.SingleResponse.class);
        com.alibaba.cola.exception.Assert.isTrue(response.isSuccess(),response.getErrMessage());
        return SingleResponse.of(singleResponse.get("data"));
    }
    /**
     * 供应商订单详情-退款审批-默认地址
     *
     * @return
     */
    @Path("defaultAddress")
    @POST
    @Operation(summary = "供应商订单详情-退款审批-默认地址", tags = CUSTOM_SERVICE)
    public SingleResponse<Map<String, Object>> defaultAddress() {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.DEFAULT_ADDRESS_URL);
        String execute = HttpClientUtil.execute(url, null);
        BOList boList = JSONObject.parseObject(execute, BOList.class);
        return  SingleResponse.of(boList.getData().get(0));

    }

    /**
     *
     *
     * @return
     */
    @Path("refundApply")
    @POST
    @Operation(summary = "售后退款-待审批-退款审批", tags = CUSTOM_SERVICE)
    public SingleResponse<Map<String, Object>> refundApply(@Parameter AgreeRefundVO dto) {
        String url = HttpClientUtil.getUrl(AppConst.ORDER_CENTER, ServiceUrlConst.REFUND_APPLY_URL);
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        String execute = HttpClientUtil.execute(url, map);
        BOList boList = JSONObject.parseObject(execute, BOList.class);
        return  SingleResponse.of(boList.getData().get(0));

    }

    @POST
    @Path("exportCanApplyForInvoicing")
    @Operation(summary = "客服工作台-客户结算-导出可申请开票", tags = CUSTOM_SERVICE)
    public SingleResponse exportCanApplyForInvoicing(@Parameter CanApplyForInvoicingDto canApplyForInvoicingDto) {
        Assert.isTrue(Objects.nonNull(canApplyForInvoicingDto),"参数不能为空");
        com.alibaba.cola.exception.Assert.isTrue(!org.springframework.util.StringUtils.isEmpty(canApplyForInvoicingDto.getExportFileType()),"文件类型不能为空");
        com.alibaba.cola.exception.Assert.isTrue(!org.springframework.util.StringUtils.isEmpty(canApplyForInvoicingDto.getCustomer()),"客户组织不能为空");

        StringBuilder querySql = new StringBuilder("select " +
                "order_customer_id," +
                "place_order_time," +
                "delivery_time," +
                "place_order_user_id," +
                "goods_id," +
                "brand," +
                "name," +
                "model," +
                "spec," +
                "quantity," +
                "order_customer_id," +
                "pretax_price," +
                "price," +
                "tax_rate," +
                "pretax_amount," +
                "amount," +
                "cost_center_name" +
                " from ordercenter.i_ordercenter_t_order_customer_goods where deleted = 0 ");
        querySql.append(" and customer_organization_id like concat('%','").append(canApplyForInvoicingDto.getCustomer().getId()).append("','%')");
        if(Objects.nonNull(canApplyForInvoicingDto.getStartDate())) {
            querySql.append(" and delivery_time >= '").append(PmUtil.dateFormatStrYYYYMMddhhmmss(canApplyForInvoicingDto.getStartDate())).append("'");
        }
        if(Objects.nonNull(canApplyForInvoicingDto.getEndDate())) {
            querySql.append(" and delivery_time <= '").append(PmUtil.dateFormatStrYYYYMMddhhmmss(canApplyForInvoicingDto.getEndDate())).append("'");
        }
        List<Map<String, Object>> data = jdbcTemplate.queryForList(querySql.toString(), Maps.newHashMap());
        if(CollectionUtils.isEmpty(data)){
            throw new BizException("查询无订单商品数据");
        }
        ReportRecord record = ReportRecord.builder()
                .code("trade_order_goods_report")
                .type(Optional.ofNullable(FileExportEnum.get(canApplyForInvoicingDto.getExportFileType())).orElseThrow(() -> new BizException("文件类型不支持")).getCode())
                .data(data.stream().map(v -> {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("customerOrderId", v.get("order_customer_id"));
                    map.put("placeOrderTime", v.get("place_order_time"));
                    map.put("deliveryTime", v.get("delivery_time"));
                    map.put("actualOrder", !org.springframework.util.StringUtils.isEmpty(v.get("place_order_user_id"))?(Objects.requireNonNull(JSON.parseObject((String)v.get("place_order_user_id"), SelectorFormat.class))).getName():"");
                    map.put("goodsId", v.get("goods_id"));
                    map.put("brand", v.get("brand"));
                    map.put("name", v.get("name"));
                    map.put("model", v.get("model"));
                    map.put("spec", v.get("spec"));
                    map.put("num", v.get("quantity").toString());
                    map.put("unit", v.get("unit"));
                    map.put("pretaxPrice", v.get("pretax_price").toString());
                    map.put("price", v.get("price").toString());
                    map.put("taxRate", v.get("tax_rate").toString());
                    map.put("pretaxTotal", Objects.isNull(v.get("pretax_amount"))?"0":v.get("pretax_amount").toString());
                    map.put("amount", Objects.isNull(v.get("amount"))?"0":v.get("amount").toString());
                    map.put("costCenterName", v.get("cost_center_name"));
                    return map;
                }).collect(Collectors.toList()))
                .build();
        Map singleResponse = RestTemplateUtil.rest(Objects.requireNonNull(PmUtil.getUrl(systemManagement)).concat(EXPORT_REPORT_URL), record, HttpMethod.POST);
        SingleResponse response = BoUtils.Map2Bo(singleResponse, SingleResponse.class);
        Assert.isTrue(response.isSuccess(),response.getErrMessage());
        return  SingleResponse.of(singleResponse.get("data"));
    }

    @POST
    @Path("exportAllOrderList")
    @Operation(summary = "客服工作台-订单-导出全部订单", tags = CUSTOM_SERVICE)
    public SingleResponse exportAllOrderList(@Parameter ExportAllOrderListDto exportAllOrderListDto) {
        Assert.isTrue(Objects.nonNull(exportAllOrderListDto),"参数不能为空");
        com.alibaba.cola.exception.Assert.isTrue(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getExportFileType()),"文件类型不能为空");

        ComplexCondition condition = new ComplexCondition();
        condition.setNature(Nature.AND);
        if (!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getOrder_customer_goods_status()))
            condition.getConditions().add(new SimpleCondition("order_customer_goods_status", Operator.EQ, exportAllOrderListDto.getOrder_customer_goods_status()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getId()))
            condition.getConditions().add(new SimpleCondition("id", Operator.EQ, exportAllOrderListDto.getId()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getCustomer_organization_id()) &&!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getCustomer_organization_id().getId()) )
            condition.getConditions().add(new SimpleCondition("customer_organization_id", Operator.LIKE, exportAllOrderListDto.getCustomer_organization_id().getId()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getPlace_order_fullname()))
            condition.getConditions().add(new SimpleCondition("place_order_fullname", Operator.EQ, exportAllOrderListDto.getPlace_order_fullname()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getCustomer_organization_name()))
            condition.getConditions().add(new SimpleCondition("customer_organization_name", Operator.EQ, exportAllOrderListDto.getCustomer_organization_name()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getAddress()))
            condition.getConditions().add(new SimpleCondition("address", Operator.EQ, exportAllOrderListDto.getAddress()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getSku()))
            condition.getConditions().add(new SimpleCondition("sku", Operator.EQ, exportAllOrderListDto.getSku()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getErp_po()))
            condition.getConditions().add(new SimpleCondition("erp_po", Operator.EQ, exportAllOrderListDto.getErp_po()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getVendor_organization_name()))
            condition.getConditions().add(new SimpleCondition("vendor_organization_name", Operator.EQ, exportAllOrderListDto.getVendor_organization_name()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getName()))
            condition.getConditions().add(new SimpleCondition("name", Operator.EQ, exportAllOrderListDto.getName()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getBrand()))
            condition.getConditions().add(new SimpleCondition("brand", Operator.EQ, exportAllOrderListDto.getBrand()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getModel()))
            condition.getConditions().add(new SimpleCondition("model", Operator.EQ, exportAllOrderListDto.getModel()));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getStart_actual_deliver_time()))
            condition.getConditions().add(new SimpleCondition("actual_deliver_time", Operator.GTE, PmUtil.dateFormatStrYYYYMMddhhmmss(exportAllOrderListDto.getStart_actual_deliver_time())));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getEnd_actual_deliver_time()))
            condition.getConditions().add(new SimpleCondition("actual_deliver_time", Operator.LTE, PmUtil.dateFormatStrYYYYMMddhhmmss(exportAllOrderListDto.getEnd_actual_deliver_time())));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getStart_place_order_time()))
            condition.getConditions().add(new SimpleCondition("place_order_time", Operator.GTE, PmUtil.dateFormatStrYYYYMMddhhmmss(exportAllOrderListDto.getStart_place_order_time())));
        if(!org.springframework.util.StringUtils.isEmpty(exportAllOrderListDto.getEnd_place_order_time()))
            condition.getConditions().add(new SimpleCondition("place_order_time", Operator.LTE, PmUtil.dateFormatStrYYYYMMddhhmmss(exportAllOrderListDto.getEnd_place_order_time())));
        if(CollectionUtils.isEmpty(condition.getConditions())){
            throw new BizException("请输入查询条件");
        }
        com.alibaba.cola.dto.SingleResponse<BOList> listByCondition = BoServiceUtils.findListByConditionByPage(CUSTOMER_ORDER_GOODS,condition,0,20);
        if(!listByCondition.isSuccess()){
            throw new BizException("订单商品数据查询异常");
        }
        if(CollectionUtils.isEmpty(listByCondition.getData().getData())){
            throw new BizException("未查询到订单商品数据");
        }
        if(listByCondition.getData().getTotal()>2000){
            throw new BizException("导出数据过多, 共".concat(listByCondition.getData().getTotal()+"").concat("条, 请重新输入查询条件以控制导出数据在2000条内!"));
        }
        com.alibaba.cola.dto.SingleResponse<BOList> listByConditionData = BoServiceUtils.findListByCondition(CUSTOMER_ORDER_GOODS,condition);
        ReportRecord record = ReportRecord.builder()
                .code("goods_list_delivered_order_goods_all_report")
                .type(Optional.ofNullable(FileExportEnum.get(exportAllOrderListDto.getExportFileType())).orElseThrow(() -> new BizException("文件类型不支持")).getCode())
                .data(listByConditionData.getData().getData().stream().map(m->{
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("customerOrderId",m.get("order_customer_id"));
                    map.put("id",m.get("id"));
                    map.put("status", OrderCustomerStatusEnum.get((String)m.get("order_customer_goods_status")).getDesc());
                    map.put("customerId",Objects.nonNull(m.get("customer_organization_id"))?CollectionUtils.firstElement((BoUtils.copy2List(m.get("customer_organization_id"),SelectorFormat.class))).getId():"");
                    map.put("customerOrgName",m.get("customer_organization_name"));
                    map.put("erpPO",m.get("erp_po"));
                    map.put("orgName",m.get("vendor_organization_name"));
                    map.put("name",m.get("name"));
                    map.put("brand",m.get("brand"));
                    map.put("model",m.get("model"));
                    map.put("spec",m.get("spec"));
                    map.put("unit",m.get("unit"));
                    map.put("packageInfo",m.get("packaging"));
                    map.put("num",Objects.isNull(m.get("quantity"))?null:((BigDecimal)m.get("quantity")).doubleValue());
                    map.put("delivery",m.get("place_order_time"));
                    map.put("pretaxPrice",Objects.isNull(m.get("pretax_price"))?null:((BigDecimal)m.get("pretax_price")).doubleValue());
                    map.put("price",Objects.isNull(m.get("price"))?null:((BigDecimal)m.get("price")).doubleValue());
                    map.put("taxRate",Objects.isNull(m.get("tax_rate"))?null:((BigDecimal)m.get("tax_rate")).doubleValue());
                    map.put("pretaxTotal",Objects.isNull(m.get("pretax_total"))?null:((BigDecimal)m.get("pretax_total")).doubleValue());
                    map.put("total",Objects.isNull(m.get("total"))?null:((BigDecimal)m.get("total")).doubleValue());
                    map.put("freight",Objects.isNull(m.get("freight"))?null:((BigDecimal)m.get("freight")).doubleValue());
                    map.put("time",m.get("place_order_time"));
                    map.put("memberName",m.get("place_order_fullname"));
                    map.put("expectedTime",m.get("createdTime"));
                    map.put("sku",m.get("sku"));
                    return map;
                }).collect(Collectors.toList()))
                .build();
        Map singleResponse = RestTemplateUtil.rest(Objects.requireNonNull(PmUtil.getUrl(systemManagement)).concat(EXPORT_REPORT_URL), record, HttpMethod.POST);
        SingleResponse response = BoUtils.Map2Bo(singleResponse, SingleResponse.class);
        Assert.isTrue(response.isSuccess(),response.getErrMessage());
        return  SingleResponse.of(singleResponse.get("data"));
    }






}